
import user from "./data/user";
import publicData from "./data/publicData";
import utils from "./utils";
import request from '@/uview-ui/libs/request/index.js'
import http from "./http.js";
class Platform {
	loginSucc = false;
    constructor(){

	}
	init(){
		// this.initAudio();
		this.checkUpdate();
		this.login(true);
	}
	/*
	  获取用户初始化数据
	*/
	getUserInfo(){
		let that = this;
		let token = wx.getStorageSync("TOKEN");
		return new Promise((resolve,reject)=>{
			if(that.loginSucc&&token){

				that.loadUserData().then(()=>{
					resolve(user);
				})
			}else{
				clearInterval(wx.checkTimer);
				wx.checkTimer = setInterval(()=>{
					token = wx.getStorageSync("TOKEN");
					if(that.loginSucc&&token){
						clearInterval(wx.checkTimer);
						that.loadUserData().then(()=>{
							resolve(user);
						})
					}
				},100);
			}
		})
	}
	loadUserData(){
		return http.init().then(res=>{
			if(res.status==0){
				user.merge(res.data.user);
				user.merge({stage:res.data.stage});
				//user.merge({stage:3})
			}
		})
	}
	getWalkData(reload=false){
		if(publicData.walkData&&!reload){
			return publicData.walkData;
		}
		return new Promise((resolve,reject)=>{
			http.walkInit().then(res=>{
				publicData.walkData = res.data;
				resolve(res.data);
			})
		})
	}
	uploadFile(file){
		return new Promise((resolve,reject)=>{
			http.ossConfig().then(res=>{
				let ossConfig = res.data;
				let fileUrl = ossConfig.dir + Math.random().toString(16).substr(2,10) +'.png';
				uni.uploadFile({
					url: ossConfig.host, //仅为示例，非真实的接口地址
					filePath:file,
					name: 'file',
					header: {
					    'content-type': 'multipart/form-data',
					},
					formData: {
						'key':fileUrl,
						'policy': ossConfig.policy,
						'OSSAccessKeyId': ossConfig.accessid, // 这里需要替换成自己的 AccessKeyId
						'success_action_status': '200', // 上传成功后的返回状态码，默认为 204
						'signature': ossConfig.signature, // 上传签名，可在服务端生成
					},
					success: (res) => {
						resolve(ossConfig.host+fileUrl)
					},
					fail(error) {
						reject(error)
					}
				});
			})

		})

	}
	async uploadMuti(list){
		let urlList = [];
		let response = await http.ossConfig();
		let ossConfig = response.data;
		return new Promise((resolve,reject)=>{
			function upload(file){
				let fileUrl = ossConfig.dir + Math.random().toString(16).substr(2,10) +'.png';
				uni.uploadFile({
					url: ossConfig.host, //仅为示例，非真实的接口地址
					filePath:file,
					name: 'file',
					header: {
					    'content-type': 'multipart/form-data',
					},
					formData: {
						'key':fileUrl,
						'policy': ossConfig.policy,
						'OSSAccessKeyId': ossConfig.accessid, // 这里需要替换成自己的 AccessKeyId
						'success_action_status': '200', // 上传成功后的返回状态码，默认为 204
						'signature': ossConfig.signature, // 上传签名，可在服务端生成
					},
					success: (res) => {
						urlList.push(ossConfig.host+fileUrl);
						if(list.length>0){
							upload(list.shift());
						}else{
							resolve(urlList)
						}
					},
					fail(error) {
						reject(error)
					}
				});
			}
			upload(list.shift());
		})
		
		/*****************************/
		
	}
	uploadFileVideo(file){
		return new Promise((resolve,reject)=>{
			http.ossConfig().then(res=>{
				let ossConfig = res.data;
				let fileUrl = ossConfig.dir + Math.random().toString(16).substr(2,10) +'.mp4';
				uni.uploadFile({
					url: ossConfig.host, //仅为示例，非真实的接口地址
					filePath:file,
					name: 'file',
					header: {
					    'content-type': 'multipart/form-data',
					},
					formData: {
						'key':fileUrl,
						'policy': ossConfig.policy,
						'OSSAccessKeyId': ossConfig.accessid, // 这里需要替换成自己的 AccessKeyId
						'success_action_status': '200', // 上传成功后的返回状态码，默认为 204
						'signature': ossConfig.signature, // 上传签名，可在服务端生成
					},
					success: (res) => {
						resolve(ossConfig.host+fileUrl)
					},
					fail(error) {
						reject(error)
					}
				});
			})

		})
	}
	toast(txt, time = 1500) {
		wx.showToast({
			title: txt,
			icon: 'none',
			duration: time
		})
	}

	copy(txt, succTxt = "复制成功") {
		wx.setClipboardData({
			data: txt,
			success: () => {
				this.toast(succTxt);
			},
			fail: (err) => {
				console.error(err);
			}
		});
	}
	showLoading(txt = '加载中') {
		wx.showLoading({
			title: txt,
			mask: true
		})
	}

	hideLoading() {
		wx.hideLoading({})
	}
	login(reset=false){
		//this.showLoading("检测登录状态");
		// wx.checkSession({
		// 	success: () => {
		// 		this.hideLoading();
		// 		let token = wx.getStorageSync("TOKEN");
		// 		if (token) {
		// 			request.config.header.Authorization = 'Bearer '+token;
		// 			this.loginSucc = true;
		// 		} else {
		// 			this.wxLogin();
		// 		}
		// 	},
		// 	fail: () => {
		// 		this.hideLoading();
		// 		this.wxLogin();
		// 	}
		// })
		let reLoginTime = wx.getStorageSync('reLoginTime');
		let currentTime = new Date().getTime();
		let token = wx.getStorageSync("TOKEN");

		if(reset||!token||!reLoginTime||reLoginTime<currentTime){
			console.info('执行重新登录！')
			this.loginSucc = false;
			this.wxLogin();
		}else{
			request.config.header.Authorization = 'Bearer '+token;
			this.loginSucc = true;
			console.info('直接缓存登录！')
		}
	}
	wxLogin(redircet=false) {
		//this.showLoading("登录中...");
		let that = this;
		return new Promise((resolve,reject)=>{
			wx.login({
				success(res0){
					let code1 = res0.code;
					wx.login({
						success(res){
							let code2 = res.code;
							http.login({code1,code2}).then(({status,data}) => {
								that.hideLoading();
								if (status != 0) {
									uni.redirectTo({
										url:'/pages/permission?identity=0'
									})
								}else{
									request.config.header.Authorization = 'Bearer '+data.accessToken;
									wx.setStorageSync("TOKEN",data.accessToken);
									that.loginSucc = true;
									if(redircet){
										let url;
										if(wx.activity){
											url = '/pages/index?name='+ wx.activity;
										}else{
											url = '/pages/welcome';
										}
										uni.redirectTo({
											url:url
										});
									}
									let reLoginTime =  + parseInt(data.expires)*1000-10000;
									wx.setStorageSync('reLoginTime',new Date().getTime()+reLoginTime);
									that.loginTimer = setTimeout(()=>{
										that.wxLogin(true);
									},reLoginTime);
								}
								resolve();
							});
						},
						fail(res){
							that.hideLoading();
							console.log("登录失败", res);
							setTimeout(() => {
								that.login();
							}, 5000)
							reject('fail');
						}
					});
				},
				fail(res){
					that.hideLoading();
					setTimeout(() => {
						that.login();
					}, 5000)
					reject('fail');
				}
			})
		})
	}
    memLogin(){
		wx.login({
			success(res1){
				let code1 = res1.code;
				wx.login({
					success(res2){
						let code2 = res2.code;
						http.memLogin({code1,code2}).then(res3=>{

						})
					}
				})
			}
		})
	}
	checkUpdate() {
		const updateManager = wx.getUpdateManager();
		updateManager.onCheckForUpdate((res) => {
			// 请求完新版本信息的回调
			console.log("是否有新版本：" + res.hasUpdate);
		});

		updateManager.onUpdateReady((res) => {
			wx.showModal({
				title: '更新提示',
				content: '新版本已经准备好，是否重启应用？',
				success(res) {
					if (res.confirm) {
						// 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
						updateManager.applyUpdate();
					}
				}
			});

		});

		updateManager.onUpdateFailed((res) => {
			// 新的版本下载失败
			console.log("新版本下载失败", res);
		});
	}

	/**
	 * 是否第一个页面
	 * @return {boolean}
	 */
	isFirstPage() {
		let pages = getCurrentPages();
		return pages.length == 1;
	}
	/**
	 * 订阅
	 */
	subscribe(tmplIds) {
		let that = this;
		let resolve2,reject2;
		function getAccept(res) {
			let resArr = [];
			for (let key of arr) {
				if (res[key] == "accept") {
					resArr.push(key);
				}
			}
			return resArr;
		}
		function guideSubscribeMessageAuth() {
			wx.getSetting({
				withSubscriptions: true,
				success: res => {
					let {
						authSetting = {},
							subscriptionsSetting: {
								mainSwitch = false,
								itemSettings = {}
							} = {}
					} = res;

					if ((authSetting['scope.subscribeMessage'] || mainSwitch)) {
						let resArr = getAccept(itemSettings);
						if (resArr.length) {
							resolve2(resArr)
							return;
						}
					}
					reject2('订阅失败')
				},
				fail: () => {
					reject2('订阅失败')
				}
			});
		}
		return new Promise((resolve,reject)=>{
			wx.requestSubscribeMessage({
				tmplIds: tmplIds,
				success(res) {
					console.log(res);
					let resArr = getAccept(res);
					if (resArr.length) {
						resolve(resArr)
					} else {
						resolve2 = resolve;
						reject2 = reject;
						guideSubscribeMessageAuth();
					}
				},
				fail() {
					reject('订阅失败')
				}
			})
		})



	}
	getAudioPlayer(src) {
		let innerAudioContext = wx.createInnerAudioContext();
		innerAudioContext.autoplay = true;
		innerAudioContext.loop = true;
		innerAudioContext.src = src;
		return innerAudioContext;
	}
}
const platform = new Platform();
export default platform;
/**********************************************/
wx['wxLogin'] = platform.wxLogin;
wx['platform'] = platform;

